package com.desire.homework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author desire
 */
public class _37_判断文件的真实类型 {
    static HashMap<String, String> filesType = new HashMap<>();

    public static void main(String[] args) {
        getAllFilesType(new File("C:\\Users\\desire\\Desktop\\javaProject\\01-javaBase\\pom.xml"));
        filesType.forEach((s, s2) -> System.out.printf("%s:%s\n", s, s2));


    }

    /**
     * 将一个文件夹的类型 全部获取 添加到 hashMap 中
     *
     * @param director
     * @return
     */
    public static void getAllFilesType(File director) {
        String k = "";
        String v = "";
        if (director.exists() && director.isDirectory()) {
            for (File file : Objects.requireNonNull(director.listFiles())) {
                if (file.isDirectory()) {
                    getAllFilesType(file);
                } else {
                    String headByte = getHeadByte(file);
                    k = headByte.substring(0, headByte.lastIndexOf(":")).trim().toUpperCase();
                    v = headByte.substring(headByte.lastIndexOf(":") + 1);
                    filesType.put(k, v);
                }
            }
        } else if (director.isFile()) {
            String headByte = getHeadByte(director);
            k = headByte.substring(0, headByte.lastIndexOf(":"));
            v = headByte.substring(headByte.lastIndexOf(":") + 1);
            filesType.put(k, v);
        } else {
            try {
                throw new FileNotFoundException("目录/文件不存在!");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取文件的真实类型
     *
     * @param file
     * @return
     */
    public static String getHeadByte(File file) {
        String info = "";
        try (FileInputStream fis = new FileInputStream(file)) {
            // 缓冲区
            byte[] buf = new byte[4];
            // 只读4个字节
            fis.read(buf, 0, buf.length);
            StringBuilder sbu = new StringBuilder();
            for (byte b : buf) {
                // 将读到的每一个字节 转换成 16进制
                sbu.append(String.format("%02x", b));
            }
            String name = file.getName();
            // 获取扩展名
            String ext = name.lastIndexOf(".") != -1 ? name.substring(name.lastIndexOf(".") + 1) : "unknow";
            info = sbu + ":" + ext;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }
}
